<template>
  <el-dialog
    :title="props.editSelectedId ? (props.isAddChildren ? '添加子级' : '编辑导航') : '添加导航'"
    v-model="dialogVisible"
    width="45%"
    :close-on-click-modal="false"
  >
    <div class="add-navigation">
      <div class="add-navigation-form ml-20px mr-20px">
        <el-form
          label-width="100px"
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-position="left"
        >
          <el-row>
            <el-col :span="23">
              <el-form-item label="导航名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入导航名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="上级导航">
                <el-tree-select
                  v-model="formData.parentId"
                  :data="superiorNavList"
                  check-strictly
                  node-key="id"
                  :props="defaultProps"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="11" class="ml-20px">
              <el-form-item label="关联类型" prop="type">
                <el-select v-model="formData.type" :min="1" @change="changeType">
                  <el-option label="分类" value="1" />
                  <el-option label="商品" value="2" />
                  <el-option label="不做关联" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="关联内容" v-if="formData.type != '3'">
            <el-button
              type="primary"
              color="#3366ff"
              @click="goAddCategory"
              v-if="formData.type == '1'"
            >
              <Icon icon="ep:plus" :size="10" />
              <span class="text-[12px]">添加分类</span>
            </el-button>
            <el-button
              type="primary"
              color="#3366ff"
              @click="goAddCommodity"
              v-if="formData.type == '2'"
            >
              <Icon icon="ep:plus" :size="10" />
              <span class="text-[12px]">选择商品</span>
            </el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="classificationList"
          style="width: 100%"
          :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
          v-if="formData.type == '1'"
        >
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column prop="name" label="分类" />
          <el-table-column prop="productCount" label="商品数量" />
          <el-table-column label="操作" width="180">
            <template #default="{ row, $index }">
              <el-button type="danger" size="small" @click="deleteCategory(row.id, $index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table
          :data="productList"
          style="width: 100%"
          :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
          v-if="formData.type == '2'"
        >
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column prop="productCover" label="商品封面">
            <template #default="{ row }">
              <img class="w-40px h-40px" :src="row.productCover" alt="" />
            </template>
          </el-table-column>
          <el-table-column prop="productTitle" label="商品" />
          <el-table-column prop="productId" label="商品ID" />
          <el-table-column prop="categoryName" label="分类" />
          <el-table-column label="操作" width="180">
            <template #default="{ row, $index }">
              <el-button type="danger" size="small" @click="deleteProduct(row.id, $index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNo"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer el-dia-btn">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" color="#3721FF" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <AddCategory
    v-if="isAddCategory"
    @close="isAddCategory = false"
    :isAddCategory="isAddCategory"
    @confirm="updateCategory"
    :classificationList="classificationList"
  />
  <!-- <AddCommodity
    v-if="isAddCommodity"
    @close="isAddCommodity = false"
    :isAddCommodity="isAddCommodity"
  /> -->
  <SelectProducts
    ref="selectProductsRef"
    :showDot="true"
    width="50%"
    title="选择商品"
    @confirm="confirmProducts"
  />
</template>

<script setup lang="ts">
defineOptions({ name: 'AddNavigation' })
import AddCategory from './addCategory.vue'
import AddCommodity from './addCommodity.vue'
import SelectProducts from '@/components/SelectProducts/index.vue'
import { WebSiteApi, WebSiteVO } from '@/api/website/website'
import { defaultProps, handleTree } from '@/utils/tree'
import { update } from 'lodash-es'
import { useDisabled } from 'element-plus'
import { throttle } from '@/utils'

const formRef = ref()
const selectProductsRef = ref()
const superiorNavList = ref<WebSiteVO[]>([])
const emit = defineEmits(['close', 'rafresh'])
const dialogVisible = ref(true)
const isAddCategory = ref(false)
// const isAddCommodity = ref(false)
const props = defineProps<{
  isAddNavigation: boolean
  webSiteId?: number | string
  editSelectedId?: number | string //编辑时选中的id
  editSelectedType?: string //编辑时选中的类型
  isAddChildren?: boolean //是否是添加子导航
  parentId?: number | string //父级id
}>()
const total = ref(0)
const queryParams = ref({
  pageSize: 10,
  pageNo: 1,
  commodityName: ''
})
const classificationList = ref([]) //分类列表
const productList = ref([]) //商品列表
const formData = ref({
  parentId: '', //上级导航，没选传0
  name: '',
  webSiteId: props.webSiteId,
  type: '1',
  categoryIds: [],
  products: []
  // classificationList: [], //分类列表
  // productList: [] //商品列表
})
const rules = {
  name: [{ required: true, message: '请输入导航名称', trigger: 'blur' }],
  navigationType: [{ required: true, message: '请选择关联类型', trigger: 'change' }]
}
// 编辑回显分类
const handleEdit = async () => {
  const res = await WebSiteApi.getWebNavigation(props.editSelectedId)
  console.log('props.isAddChildren', props.isAddChildren)

  if (props.isAddChildren) {
    formData.value.parentId = res.id
  } else {
    formData.value = res
    formData.value.type = res.type.toString()
    formData.value.parentId =  res.parentId
    if (res.type == '1') {
      WebSiteApi.getWebNavigationCategoryPage({
        webNavId: props.editSelectedId,
        pageNo: 1,
        pageSize: 10
      }).then((res) => {
        classificationList.value = res?.list.map((item) => {
          return {
            id: item.productCategoryId,
            webNavId: item.webNavId,
            name: item.categoryName,
            productCount: item.productCount
          }
        })
      })
    } else {
      await WebSiteApi.getWebNavigationProductPage({
        webNavId: props.editSelectedId,
        pageNo: 1,
        pageSize: 10
      }).then((res) => {
        productList.value = res?.list
      })
    }
  }
}
// 编辑回显商品
// const handleEditProduct = async () => {}
//
const submit = throttle(() => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log(formData.value)
      formData.value.parentId = formData.value.parentId == '' ? '0' : formData.value.parentId
      if (formData.value.type == '1') {
        formData.value.categoryIds = classificationList.value.map((item) => item.id)
      } else {
        console.log(productList.value, 'productList.value')

        formData.value.products = productList.value.map((item) => {
          return {
            productId: item.productId
            // categoryId: item.categoryId
          }
        })
        console.log(formData.value.products, 'formData.value.products')
      }
      if (formData.value.id) {
        delete formData.value.associatedContent
        delete formData.value.associatedCount
        WebSiteApi.updateWebNavigation(formData.value).then((res) => {
          ElMessage({
            message: '编辑成功',
            type: 'success'
          })
          dialogVisible.value = false
          // 刷新父页面的list
          emit('rafresh')
        })
      } else {
        WebSiteApi.createWebNavigation(formData.value).then((res) => {
          ElMessage({
            message: '添加成功',
            type: 'success'
          })
          dialogVisible.value = false
          // 刷新父页面的list
          emit('rafresh')
        })
      }
    }
  })
}, 1000)
// 分类删除
const deleteCategory = (id, idx) => {
  // if (formData.value.id) {
  // } else {
  classificationList.value.splice(idx, 1)
  // }
}
// 商品删除
const deleteProduct = (id, idx) => {
  // if (formData.value.id) {
  // } else {
  productList.value.splice(idx, 1)
  // }
}
// 获得导航设置树形结构
const handleGetWebNavigationTree = async () => {
  WebSiteApi.getWebNavigationTree({ webSiteId: props.webSiteId }).then((res) => {
    superiorNavList.value = res
    superiorNavList.value.unshift({
      id: 0,
      name: '无'
    })
    console.log(superiorNavList.value)
  })
}
// 获取商品数据
const confirmProducts = (data) => {
  let newPro = data.map((item) => {
    return {
      productTitle: item.titleExternal,
      productId: item.id,
      categoryId: item.categoryId,
      categoryName: item.categoryName,
      productCover: item.cover,
      webNavId: item.webNavId,
      cover: item.cover
    }
  })
  productList.value = productList.value.concat(newPro)
}
// 切换关联类型
const changeType = (val) => {
  val == '1' ? (productList.value = []) : (classificationList.value = [])
}
// 添加分类
const updateCategory = (data) => {
  console.log(data)

  // productCount: item.productCount
  if (formData.value.type == '1') {
    classificationList.value.push(...data)
  } else {
    productList.value.push(...data)
  }
}
const goAddCategory = () => {
  isAddCategory.value = true
}
const goAddCommodity = () => {
  // isAddCommodity.value = true
  selectProductsRef.value?.show()
}
watch(dialogVisible, (val) => {
  if (!val) {
    emit('close')
  }
})
watch(
  () => props.isAddNavigation,
  (val) => {
    dialogVisible.value = val
  }
)
onMounted(() => {
  if (props.editSelectedId) {
    handleEdit()
  }
  handleGetWebNavigationTree()
})
</script>

<style scoped>
@import '@/styles/website.scss';
/* 将必填星号移动到标签后面 */
:deep(.el-form-item.is-required .el-form-item__label::before) {
  display: none !important; /* 隐藏默认的前置星号 */
}

:deep(.el-form-item.is-required .el-form-item__label::after) {
  content: '*';
  color: var(--el-color-danger);
  margin-left: 4px;
}
</style>
